package com.woquyin.controller.api;

import java.util.HashMap;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.json.FastJson;
import com.woquyin.common.Constance;
import com.woquyin.interceptor.ApiAuthInterceptor;
import com.woquyin.interceptor.ParamInterceptor;
import com.woquyin.model.BizTemplet;
import com.woquyin.model.SecUser;
import com.woquyin.vo.ReturnData;
import com.woquyin.vo.templet.SaveVo;

/**
 * 模版相关接口
 * 
 * @author heem
 * @create time 创建时间：2017年9月12日 下午9:20:05
 * @version 1.0
 * @since
 */
@Before(ApiAuthInterceptor.class)
public class TempletController extends Controller {

	/**
	 * 保存模版
	 */
	public void save() {
		ReturnData<String> resp = new ReturnData<String>();
		// 新增或者修改模板
		String jsonString = getAttrForStr(ParamInterceptor.REQUEST_JSON);
		SaveVo saveVo = FastJson.getJson().parse(jsonString, SaveVo.class);
		BizTemplet.dao.saveTemplet(saveVo);
		renderJson(resp);
	}

	/**
	 * 获取模版
	 */
	public void get() {
		ReturnData<BizTemplet> resp = new ReturnData<>();
		String jsonString = getAttrForStr(ParamInterceptor.REQUEST_JSON);
		HashMap<String, String> req = FastJson.getJson().parse(jsonString, HashMap.class);
		resp.setData(BizTemplet.dao.findById(req.get("id")));
		renderJson(resp);
	}

	/**
	 * 通过发布的模版获取模版
	 */
	public void useTemplet() {
		ReturnData<BizTemplet> resp = new ReturnData<>();
		String jsonString = getAttrForStr(ParamInterceptor.REQUEST_JSON);
		HashMap<String, String> req = FastJson.getJson().parse(jsonString, HashMap.class);
		String pubTempletId = req.get("pubTempletId");
		String token = req.get("token");
		SecUser loginUser = (SecUser)getSession().getAttribute("userInfo");
		if(BizTemplet.dao.getByPublishId(pubTempletId,loginUser.getId())!=null){
			resp.setCode(Constance.WholeStateCodeEnum.OTHER_ERROR.getCode());
			resp.setMsg("您已经拥有该模版，请在我的模版里面选择使用");
			renderJson(resp);
		}else{
			BizTemplet pubTemplet = BizTemplet.dao.findById(pubTempletId);
			SaveVo templetSaveVo = new SaveVo();
			templetSaveVo.setFormatTypeCode(pubTemplet.getFormatTypeCode());
			templetSaveVo.setImgUrl(pubTemplet.getImgUrl());
			templetSaveVo.setSourceTempletId(pubTemplet.getId());
			templetSaveVo.setName(pubTemplet.getName());
			templetSaveVo.setToken(token);
			BizTemplet bizTemplet = BizTemplet.dao.saveTemplet(templetSaveVo);
			if(bizTemplet!=null){
				resp.setData(bizTemplet);	
			}else{
				resp.setCode(Constance.WholeStateCodeEnum.OTHER_ERROR.getCode());
				resp.setMsg("获取模版失败");
			}
			renderJson(resp);
		}
	}

}
